package jvs.vfs.tools;

import java.io.Serializable;
import java.util.Arrays;
import java.util.Map;
import java.util.TreeMap;

import javax.swing.event.TreeModelEvent;
import javax.swing.tree.TreePath;

import jvs.vfs.FileSystem;
import x.java.io.File;

/**
 *@author qiangli
 */
public class FileSystemModel extends AbstractTreeModel implements Serializable {

	private static final long serialVersionUID = 1L;

	private FileSystem fs = FileSystem.getFileSystem();
	
	private Map<File, File[]> cached = new TreeMap<File, File[]>();
	
	public FileSystemModel() {
	}

	public Object getRoot() {
		return fs.getRoot();
	}
	
	private synchronized File[] load(Object parent) {
		File dir = (File) parent;
		File[] children = cached.get(dir);
		
		if (children == null) {
			children = (File[])dir.listFiles();
			if (children == null) {
				children = new File[0];
			} else {
				Arrays.sort(children);
			}
			cached.put(dir, children);
		} else {
		System.out.println("found cached: "+children.length);
		}
		return children;
	}

	public Object getChild(Object parent, int index) {
		File[] children = load(parent);
		return children[index];
	}

	public int getChildCount(Object parent) {
		File file = (File) parent;
	
		int count = 0;
		if (file.isDirectory()) {
			File[] children = load(parent);
			count = children.length;
		} 
		return count;
	}

	public boolean isLeaf(Object node) {
		return !((File) node).isDirectory();
	}

	public void valueForPathChanged(TreePath path, Object newValue) {
		//
	}

	public int getIndexOfChild(Object parent, Object child) {
		File[] children = load(parent);
		
		File file = (File) child;
		int result = -1;
		for (int i = 0; i < children.length; i++) {
			if (file.getName().equals(children[i].getName())) {
				result = i;
				break;
			}
		}
		return result;
	}

	@Override
	public void fireTreeStructureChanged(TreeModelEvent e) {
		cached.clear(); //TODO selective clear?
		super.fireTreeStructureChanged(e);
	}
}
